package com.huazai.study;

import java.lang.annotation.*;
import java.lang.reflect.Field;

public class 反射操作注解 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class<?> c1 = Class.forName("com.huazai.study.Student");

        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获取注解中的value值
        tableHuazai Huazai = c1.getAnnotation(tableHuazai.class);
        String HuazaiValue = Huazai.value();
        System.out.println(HuazaiValue);

        //获得类指定的注解
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);
        fieldHuazai huazaiName = name.getAnnotation(fieldHuazai.class);

        System.out.println(huazaiName.columnName() + "  " +
                huazaiName.type() + "  " + huazaiName.length() );

    }

}

@tableHuazai("DB_Stu")
class Student {
    @fieldHuazai(columnName = "id",type = "int",length = 18)
    private int id;
    @fieldHuazai(columnName = "age",type = "int",length = 18)
    private int age;
    @fieldHuazai(columnName = "name",type = "String",length = 18)
    private String name;

}

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface tableHuazai {
    String value() default "";
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface fieldHuazai {
    String columnName() default "";
    String type() default "";
    int length() default 0;
}